import '../style/components.scss'
import Vue from 'vue'
import Vuex from 'vuex'
import VueRouter from 'vue-router'
import routes from '../vue/router/index'
import components from '../vue/components/index'
import storeModal from '../vue/store/modal'
import storeBridge from '../vue/store/bridge'
import storeUser from '../vue/store/user'
import Cookies from 'js-cookie'
const mapState = Vuex.mapState
Vue.use(VueRouter)
Vue.use(Vuex)
Object.keys(components).forEach((key) => {
  const component = components[key]
  const _key = key.replace(/[A-Z]/, '-$1')
  Vue.component(_key, component)
})
const router = new VueRouter({
  routes,
  linkActiveClass: 'active',
  linkExactActiveClass: 'exact-active'
})
router.beforeEach((to, from, next) => {
  const token = Cookies.get('token')
  if (!token) {
    if (!/^\/login/.test(to.path)) {
      next({
        path: '/login'
      })
    } else {
      next()
    }
  } else {
    if (/^\/login/.test(to.path)) {
      const roles = Cookies.get('roles')
      next({
        path: `/${roles}`
      })
    } else {
      next()
    }
  }
})
router.afterEach((to, from) => {
  if (/^\/teacher/.test(to.path)) {
    $('.modal-wrap').addClass('teacher')
  } else {
    $('.modal-wrap').removeClass('teacher')
  }
})
const store = new Vuex.Store({
  modules: {
    modal: storeModal,
    bridge: storeBridge,
    user: storeUser
  }
})
router.afterEach((to, from) => {
  if (to.path === '/') {
    router.push('/login')
  }
})
if (module.hot) {
  module.hot.accept(['../vue/store/modal'], () => {
    const newModal = require('../vue/store/modal').default
    const newBridge = require('../vue/store/bridge').default
    const newUser = require('../vue/store/user').default
    store.hotUpdate({
      modules: {
        modal: newModal,
        bridge: newBridge,
        user: newUser
      }
    })
  })
}
var app = new Vue({
  el: '#app',
  router,
  store,
  computed: mapState({
    user: state => state.user.user
  }),
  created () {
    if (!this.$store.state.user.user.token && Cookies.get('token')) {
      this.$store.commit('postUser', {
        id: Cookies.get('id'),
        token: Cookies.get('token'),
        roles: Cookies.get('roles'),
        name: Cookies.get('name')
      })
    }
    this.$store.dispatch('getUserInfo')
    if (this.$route.path === '/') {
      this.$router.replace('/login')
    }
  }
})

export default app
